<template>
  <div class="amap-container">
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map"></div>

    <!-- 地图控制面板 -->
    <div v-if="showControls" class="map-controls">
      <button @click="zoomIn" class="control-btn" title="放大">➕</button>
      <button @click="zoomOut" class="control-btn" title="缩小">➖</button>
      <button @click="centerMap" class="control-btn" title="回到中心">
        📍
      </button>
      
      <button
        @click="isShowSatellite"
        class="control-btn"
        title="显示卫星图"
      >
        🚋
      </button>
      <button
        @click="isHideSatellite"
        class="control-btn"
        title="隐藏卫星图"
      >
        🚋
      </button>

      <!-- 热力图开关 -->
      <button
        @click="toggleHeatmap"
        class="control-btn"
        :class="{ active: showHeatmap }"
        :title="showHeatmap ? '关闭热力图' : '打开热力图'"
      >
        🔥
      </button>
      <!-- 地铁线路开关 -->
      <button
        @click="toggleSubwayList()"
        class="control-btn"
        :class="{ active: showSubway }"
        :title="showSubway ? '隐藏地铁线路' : '显示地铁线路'"
      >
        🚋
      </button>
      <!-- 公交线路开关 -->
      <button
        @click="toggleBusList()"
        class="control-btn"
        :class="{ active: showBus }"
        :title="showBus ? '隐藏公交线路' : '显示公交线路'"
      >
        🚌
      </button>
      <!-- 区域名称开关 -->
      <button
        @click="toggleDistricts()"
        class="control-btn"
        :class="{ active: showDistricts }"
        :title="showDistricts ? '隐藏区域名称' : '显示区域名称'"
      >
        📍
      </button>
      <!-- 打开关闭标点 -->
      <button
        @click="markersShow"
        class="control-btn"
        :class="{ active: isShowMarkers }"
        :title="isShowMarkers ? '隐藏标记点' : '显示标记点'"
      >
        🛣️
      </button>

      <!-- 打开路线 -->
      <button
        @click="toggleRoute()"
        class="control-btn"
        :class="{ active: showToggle }"
        :title="showToggle ? '隐藏路线' : '显示路线'"
      >
        🚇
      </button>
      <button
        @click="toggleLundu()"
        class="control-btn"
        :class="{ active: showLundu }"
        :title="showLundu ? '隐藏轮渡' : '显示轮渡'"
      >
        🚢
      </button>
      <!-- 🚢 -->
      <button
        @click="searchAndDrawBinjiangBoundary()"
        class="control-btn"
        :class="{ active: BinjiangBoundary }"
        :title="BinjiangBoundary ? '隐藏滨江区' : '显示滨江区'"
      >
        🏙️
      </button>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span>地图加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-overlay">
      <span>❌ 地图加载失败，请检查API密钥</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,shallowRef , onUnmounted, watch, nextTick, version } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: import.meta.env.VITE_AMAP_SECURITY_JS_CODE,
};

// 防抖函数
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(this, args), delay)
  }
}

// 节流函数
const throttle = (fn, delay) => {
  let lastCall = 0
  return (...args) => {
    const now = Date.now()
    if (now - lastCall >= delay) {
      lastCall = now
      fn.apply(this, args)
    }
  }
}

// Props
const props = defineProps({
  center: {
    type: Array,
    // 杭州市
    default: () => [120.153576, 30.287459], // 杭州市中心坐标
  },
  zoom: {
    type: Number,
    default: 13,
  },
  showControls: {
    type: Boolean,
    default: true,
  },
  markers: {
    type: Array,
    default: () => [],
  },
});

// Emits
const emit = defineEmits([
  "map-loaded",
  "marker-click",
  "map-click",
  "heatmap-toggle",
]);

// Refs
const mapContainer = shallowRef(null);
const map = shallowRef(null);
const isSatellite = ref(false);
const markerInstances = shallowRef([]);
const heatmap = ref(null);
const showHeatmap = ref(false);
const loading = ref(true);
const error = ref(false);
const isShowMarkers = ref(false);
const showToggle = ref(false);
const satelliteLayer = shallowRef(null);
const satellite = ref(null);
const subwayLinesObj = ref({}); // 存储所有地铁线路
const lines = ["地铁1号线", "地铁4号线", "地铁5号线", "地铁6号线"];
subwayLinesObj.value = lines.reduce((acc, line) => {
  acc[line] = [];
  return acc;
}, {});
const lineSearch = shallowRef(null); // 线路搜索实例
// 自定义的线
const myLine = shallowRef(null);
const lundulineSpolyline = shallowRef(null);
const showLundu = ref(false);
const lunduLines = [
  [120.228456, 30.238765],
  [120.225678, 30.236543],
  [120.220123, 30.232109],
  [120.215876, 30.228765],
  [120.210123, 30.225109],
  [120.205123, 30.220109],
  [120.200123, 30.215109],
  [120.18123, 30.210109],
  [120.1749223, 30.208109],
];
// 地铁线路相关
const showSubway = ref(false);
// 公交线路相关
const showBus = ref(false);
const busLinesObj = ref({
  "1507M": [],
  113: [],
});
// 显示区域名称和圆形透明块相关
const showDistricts = ref(false);
const districtMarkers = shallowRef([]); // 存储区域名称标记

// 初始化地图
const initMap = async () => {
  // 防止重复初始化
  if (map.value) return;
  try {
    loading.value = true;
    error.value = false;
    console.log("import.meta.env.VITE_AMAP_KEY", import.meta.env.VITE_AMAP_KEY);
    const AMap = await AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY || "你的高德地图Key",
      version: "2.0",
      plugins: [
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.MapType",
        "AMap.HeatMap",
        "AMap.TileLayer",
        "AMap.LineSearch",
        "AMap.DistrictSearch",
        "AMap.Polygon",
      ],
    });

    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      viewMode: "2D",
      zoom: props.zoom,
      center: props.center,
      mapStyle: "amap://styles/grey", // 确保地图样式正确
      zooms: [10, 18], // 限制缩放级别范围
      pitch: 0, // 禁用倾斜
      rotation: 0, // 禁用旋转
      animate: false, // 禁用动画
      doubleClickZoom: false, // 禁用双击缩放
      // 禁用滚轮缩放
      // scrollWheel: false,
      features: ["bg", "point", "road"], // 添加地图要素

      optimize: true,
      lazyLoad: true,
      expandZoomRange: true,
    });

    satellite.value = new AMap.TileLayer.Satellite({
      map: null,
    });
    // 添加控件 - 确保地图有内容
    // map.value.addControl(new AMap.ToolBar({
    //   position: 'LT' // 左上角
    // }))
    // map.value.addControl(new AMap.Scale({
    //   position: 'LB' // 左下角
    // }))
    // 绑定事件
    map.value.on("click", (e) => {
      emit("map-click", e.lnglat);
    });

    // 地图加载完成事件
    map.value.on("complete", () => {
      console.log("地图加载完成！");
      loading.value = false;
    });
    satelliteLayer.value = new window.AMap.TileLayer.Satellite();
    // 隐藏卫星
    satelliteLayer.value.hide();
    // 初始化地铁
    lineSearch.value = new AMap.LineSearch({
      pageIndex: 1,
      pageSize: 10,
      //杭州 滨江
      city: "杭州市",
      citylimit: false,

      extensions: "all",
    });

    // 创建热力图实例的正确方式
    heatmap.value = new AMap.HeatMap(map.value, {
      radius: 25, // 热力图点半径
      opacity: [0, 0.8], // 热力图透明度范围
      gradient: {
        0.4: "blue",
        0.6: "cyan",
        0.7: "lime",
        0.8: "yellow",
        1.0: "red",
      },
    });
    toggleDistricts();
    emit("map-loaded", map.value);
  } catch (error) {
    console.error("高德地图加载失败:", error);
    loading.value = false;
    error.value = true;
  }
};
const initLundu = () => {
  const AMap = window.AMap;
  if (!AMap) return null;

  const polyline = new AMap.Polyline({
    map: map.value,
    path: lunduLines,
    strokeColor: "#0CDDE4", // 根据线路名称获取颜色
    strokeOpacity: 0.8,
    strokeWeight: 6,
    //虚线
    strokeStyle: "dashed",
    strokeDasharray: [10, 5], // 虚线
  });

  // 存储线路信息
  polyline.lineName = "轮渡线路";

  return polyline;
};
const BinjiangBoundary = ref(false);
const binjiangqupolygon = shallowRef(null);
// 搜索并绘制滨江区的行政规划图
const searchAndDrawBinjiangBoundary = () => {
  BinjiangBoundary.value = !BinjiangBoundary.value;
  const AMap = window.AMap;
  if (!AMap || !map.value) return;
  // 使用DistrictSearch查询区级边界
  const districtSearch = new AMap.DistrictSearch({
    level: "district",
    subdistrict: 0, // 不返回下级行政区
    city: "杭州",
    extensions: "all", // 返回边界坐标
  });
  if (!BinjiangBoundary.value) {
    map.value.remove(binjiangqupolygon.value);
    binjiangqupolygon.value.hide;
    return;
  }
  // 搜索“杭州市滨江区”
  districtSearch.search("滨江区", function (status, result) {
    if (status === "complete") {
      var district = result.districtList[0];
      if (district && district.boundaries) {
        // 滨江区的边界可能由多个多边形组成，我们通常取第一个主边界
        var boundary = district.boundaries[0];

        // 创建多边形覆盖物
        console.log("boundary", boundary);
        // 解决  Uncaught Invalid Object: Pixel(NaN, NaN)
        boundary = boundary.map((item) => {
          return [item.lng, item.lat];
        });
        console.log("boundary", boundary);
        binjiangqupolygon.value = new AMap.Polygon({
          path: boundary,
          strokeColor: "#B3EBAF", // 线颜色
          strokeWeight: 2, // 线宽
          fillColor: "#B3EBAF", // 填充色
          fillOpacity: 0.35, // 填充透明度
        });
        // 将多边形添加到地图上
        map.value.add(binjiangqupolygon.value);
        binjiangqupolygon.value.show();
      } else {
        console.log("未找到滨江区边界数据");
      }
    } else {
      console.log("行政区查询失败：" + status);
    }
  });
};
const toggleLundu = () => {
  showLundu.value = !showLundu.value;
  if (showLundu.value) {
    lundulineSpolyline.value = initLundu();
    lundulineSpolyline.value.show();
  } else {
    map.value.remove(lundulineSpolyline.value);
  }
};
// init 地铁
const initSubway = async (name = null) => {
  console.log("initSubway1", name);
  if (!lineSearch.value || !map.value) return;

  try {
    // 搜索杭州地铁1号线:cite[5]
    lineSearch.value.search(name, (status, result) => {
      if (status === "complete" && result.info === "OK") {
        console.log(`地铁${name}查询成功:`, result);

        // 绘制所有找到的线路
        if (result.lineInfo && result.lineInfo.length > 0) {
          result.lineInfo.forEach((lineInfo, index) => {
            if (lineInfo.path && lineInfo.path.length > 0) {
              let path = extractBinjiangSection(
                lineInfo.path,
                binjiangBoundary.value
              );
              console.log("path", path);
              if (path && path.length > 0) {
                const polyline = drawSubwayLine(path, name);
                subwayLinesObj.value[name].push(polyline);
                // 默认隐藏地铁线路
                polyline.show();
              }
            }
          });

          console.log(
            `成功加载 ${subwayLinesObj.value[name].length} 条地铁线路`
          );
        }
      } else {
        console.error("地铁查询失败:", status, result);
      }
    });
  } catch (error) {
    console.error("初始化地铁线路失败:", error);
  }
};
const drawMyLine = (path, lineName) => {
  const AMap = window.AMap;
  if (!AMap) return null;

  const polyline = new AMap.Polyline({
    map: map.value,
    path: path,
    strokeColor: "#E67818", // 根据线路名称获取颜色
    strokeOpacity: 0.8,
    strokeWeight: 6,
    strokeStyle: "solid",
    strokeDasharray: [0, 0], // 实线
  });

  // 存储线路信息
  polyline.lineName = lineName;

  return polyline;
};
// 绘制地铁线路:cite[5]:cite[6]
const drawSubwayLine = (path, lineName) => {
  const AMap = window.AMap;
  if (!AMap) return null;

  const polyline = new AMap.Polyline({
    map: map.value,
    path: path,
    strokeColor: getLineColor(lineName), // 根据线路名称获取颜色
    strokeOpacity: 0.8,
    strokeWeight: 6,
    strokeStyle: "solid",
    strokeDasharray: [0, 0], // 实线
  });

  // 存储线路信息
  polyline.lineName = lineName;

  return polyline;
};

// 根据线路名称获取颜色
const getLineColor = (lineName) => {
  console.log("lineName", lineName);
  const colorMap = {
    地铁1号线: "#E12311",
    地铁2号线: "#BF8157",
    地铁3号线: "#037AC1",
    地铁4号线: "#83C21F",
    地铁5号线: "#E67818",
    地铁6号线: "#291771",
    地铁7号线: "#9267A6",
    地铁8号线: "#808080",
    地铁9号线: "#FFD700",
    地铁10号线: "#00CED1",
    地铁16号线: "#FF4500",
    地铁19号线: "#fff",
  };

  return colorMap[lineName] || "#3366FF"; // 默认蓝色
};
const clearLine = () => {
  map.value.remove(myLine.value);
};
const toggleRoute = (
  ls = [
    [120.190826, 30.194148],
    [120.186623, 30.16643],
    [120.1685231311056, 30.161578213867102],
  ]
) => {
  showToggle.value = !showToggle.value;
  if (showToggle.value) {
    myLine.value = drawMyLine(ls, "地铁1号线");
    console.log("myLine.value", myLine.value);
    myLine.value.show();
  } else {
    clearLine();
  }
};
// 清除所有地铁线路
const clearSubwayLines = () => {
  // if (map.value && subwayLines.value.length > 0) {
  //   subwayLines.value.forEach((polyline) => {
  //     map.value.remove(polyline);
  //   });
  //   subwayLines.value = [];
  // }
  if (map.value && subwayLinesObj.value) {
    Object.keys(subwayLinesObj.value).forEach((key) => {
      subwayLinesObj.value[key].forEach((polyline) => {
        map.value.remove(polyline);
      });
      subwayLinesObj.value[key] = [];
    });
  }
};

// 显示/隐藏地铁线路
const toggleSubwayList = async (names = lines) => {
  showSubway.value = !showSubway.value;
  console.log("names", names);
  await getBinjiangBoundary();
  names.forEach((name) => {
    toggleSubway(name);
  });
};
const toggleSubway = (name = "一号线") => {
  if (showSubway.value) {
    if (subwayLinesObj.value[name].length === 0) {
      // 清除之前的地铁线路
      clearSubwayLines();
      // 如果还没有加载地铁线路，先初始化
      initSubway(name).then(() => {
        // 加载完成后显示
        subwayLinesObj.value[name].forEach((polyline) => {
          polyline.show();
        });
      });
    } else {
      // 直接显示已有线路
      subwayLinesObj.value[name].forEach((polyline) => {
        polyline.show();
      });
    }
  } else {
    // 隐藏地铁线路
    subwayLinesObj.value[name].forEach((polyline) => {
      polyline.hide();
    });
  }
};

// 在toggleSubway方法后面添加公交线路相关方法

// init 公交
const initBus = async (name = null) => {
  console.log("initBus", name);
  if (!lineSearch.value || !map.value) return;

  try {
    // 搜索公交线路
    lineSearch.value.search(name, (status, result) => {
      if (status === "complete" && result.info === "OK") {
        console.log(`公交${name}查询成功:`, result);

        // 绘制所有找到的线路
        if (result.lineInfo && result.lineInfo.length > 0) {
          result.lineInfo.forEach((lineInfo, index) => {
            if (lineInfo.path && lineInfo.path.length > 0) {
              // 使用extractBinjiangSection过滤出滨江区域内的线路
              let path = extractBinjiangSection(
                lineInfo.path,
                binjiangBoundary.value
              );
              console.log("bus path", path);
              if (path && path.length > 0) {
                const polyline = drawBusLine(path, name);
                busLinesObj.value[name].push(polyline);
                // 默认显示公交线路
                polyline.show();
              }
            }
          });

          console.log(`成功加载 ${busLinesObj.value[name].length} 条公交线路`);
        }
      } else {
        console.error("公交查询失败:", status, result);
      }
    });
  } catch (error) {
    console.error("初始化公交线路失败:", error);
  }
};

// 绘制公交线路
const drawBusLine = (path, lineName) => {
  const AMap = window.AMap;
  if (!AMap) return null;

  const polyline = new AMap.Polyline({
    map: map.value,
    path: path,
    strokeColor: getBusLineColor(lineName), // 根据线路名称获取颜色
    strokeOpacity: 0.8,
    strokeWeight: 4,
    strokeStyle: "solid",
    strokeDasharray: [0, 0], // 实线
  });

  // 存储线路信息
  polyline.lineName = lineName;

  return polyline;
};

// 根据公交线路名称获取颜色
const getBusLineColor = (lineName) => {
  const colorMap = {
    "1507M": "#0CB5BC", // 红色
    113: "#FF4500", // 蓝色
  };

  return colorMap[lineName] || "#FFA500"; // 默认橙色
};

// 清除所有公交线路
const clearBusLines = () => {
  if (map.value && busLinesObj.value) {
    Object.keys(busLinesObj.value).forEach((key) => {
      busLinesObj.value[key].forEach((polyline) => {
        map.value.remove(polyline);
      });
      busLinesObj.value[key] = [];
    });
  }
};

// 显示/隐藏公交线路
const toggleBusList = async (names = ["1507M", "113"]) => {
  showBus.value = !showBus.value;
  await getBinjiangBoundary();
  names.forEach((name) => {
    toggleBus(name);
  });
};

const toggleBus = (name) => {
  if (showBus.value) {
    if (busLinesObj.value[name].length === 0) {
      // 清除之前的公交线路
      clearBusLines();
      // 如果还没有加载公交线路，先初始化
      initBus(name).then(() => {
        // 加载完成后显示
        busLinesObj.value[name].forEach((polyline) => {
          polyline.show();
        });
      });
    } else {
      // 直接显示已有线路
      busLinesObj.value[name].forEach((polyline) => {
        polyline.show();
      });
    }
  } else {
    // 隐藏公交线路
    busLinesObj.value[name].forEach((polyline) => {
      polyline.hide();
    });
  }
};

//判断浏览区是否支持canvas
function isSupportCanvas() {
  var elem = document.createElement("canvas");
  return !!(elem.getContext && elem.getContext("2d"));
}
// 切换热力图显示

// 切换热力图显示
const toggleHeatmap = () => {
  showHeatmap.value = !showHeatmap.value;
  const heatDataEffect = {
    max: 20,
    data: [
      { lng: 120.153576, lat: 30.159326, count: 10 },
      { lng: 120.148952, lat: 30.162456, count: 8 },
      { lng: 120.157891, lat: 30.166789, count: 15 },
      { lng: 120.168945, lat: 30.172345, count: 20 },
      { lng: 120.155678, lat: 30.164567, count: 11 },
      { lng: 120.150123, lat: 30.16789, count: 8 },
      { lng: 120.165432, lat: 30.160987, count: 13 },
      { lng: 120.158456, lat: 30.162345, count: 6 },

      { lng: 120.172345, lat: 30.238765, count: 9 },
      { lng: 120.198765, lat: 30.252345, count: 22 },
      { lng: 120.176543, lat: 30.234567, count: 7 },
      { lng: 120.129876, lat: 30.242345, count: 20 },
      { lng: 120.137654, lat: 30.249876, count: 25 },
      { lng: 120.134321, lat: 30.235678, count: 10 },
      { lng: 120.131234, lat: 30.244321, count: 17 },
    ],
  };
  console.log("showHeatmap", showHeatmap.value);
  if (heatmap.value) {
    if (showHeatmap.value) {
      heatmap.value.setDataSet(heatDataEffect);
      console.log("heatmap.value", heatmap.value);
      heatmap.value.show();
    } else {
      heatmap.value.hide();
    }
  }
};

const markersShow = () => {
  isShowMarkers.value = !isShowMarkers.value;
  if (isShowMarkers.value) {
    // 确保在显示标记点时能正确获取AMap对象
    addMarkers(window.AMap);
  } else {
    clearMarkers();
  }
};
// 添加标记点
const addMarkers = (AMap) => {
  // 确保AMap对象可用
  const AMapInstance = AMap || window.AMap;
  if (!AMapInstance || !map.value || !props.markers.length) return;

  clearMarkers();

  props.markers.forEach((markerData) => {
    const marker = new AMapInstance.Marker({
      position: markerData.position,
      title: markerData.title,
      content: createMarkerContent(markerData),
      offset: new AMapInstance.Pixel(-13, -30),
    });

    marker.on("click", () => {
      console.log("markerData", markerData);
      sendMessageToCSharp({
        type: "marker",
        id: markerData.id,
        name: markerData.title,
        position: markerData.position,
      });
    });

    map.value.add(marker);
    markerInstances.value.push(marker);
  });
};

// 创建标记点内容
const createMarkerContent = (markerData) => {
  // 如果标记点数据包含useIconImage属性，则使用IconImage组件
  if (markerData.useIconImage) {
    return `<div class="icon-image-marker" style="width:81px;height:97px;position:relative;display:flex;justify-content:center">
     <img src="${markerData.bgIconImage}" alt="${markerData.title}" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 1;">
      <img src="${markerData.iconImage}" alt="${markerData.title}" style="width: 40px;height:40px;margin-top:23px; position: relative; z-index: 2;">
    </div>`;
  }

  // 默认标记点样式
  return `<div style="
    background: #ff4444;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    white-space: nowrap;
  ">${markerData.title}</div>`;
};

// 清除所有标记
const clearMarkers = () => {
  if (map.value && markerInstances.value.length) {
    map.value.remove(markerInstances.value);
    markerInstances.value = [];
  }
};

// 地图控制方法
const zoomIn = () => map.value?.zoomIn();
const zoomOut = () => map.value?.zoomOut();

const centerMap = () => {
  if (map.value) {
    map.value.setCenter(props.center);
    map.value.setZoom(props.zoom);
  }
};

const toggleSatellite = (bool) => {
  if (map.value) {
    isSatellite.value = bool;
    if (isSatellite.value) {
      satellite.value.setMap(map.value);
    } else {
      satellite.value.setMap(null);
    }
  }
};
// 显示卫星图
const isShowSatellite = () => {
  if (!map.value) return;
  isSatellite.value = true;
  if (isSatellite.value) {
    satellite.value.setMap(map.value);
  }
};
// 隐藏卫星图
const isHideSatellite = () => {
  if (!map.value) return;
  isSatellite.value = false;
  if (!isSatellite.value) {
    satellite.value.setMap(null);
  }
};
// 滨江
const districtSearch = ref(null);
const binjiangBoundary = ref(null);
function getBinjiangBoundary() {
  return new Promise((resolve, reject) => {
    // 使用DistrictSearch查询区级边界
    districtSearch.value = new AMap.DistrictSearch({
      level: "district",
      subdistrict: 0, // 不返回下级行政区
      extensions: "all", // 返回边界坐标
    });
    // 搜索“杭州市滨江区”
    districtSearch.value.search("滨江区", function (status, result) {
      if (status === "complete") {
        var district = result.districtList[0];
        if (district && district.boundaries) {
          // 滨江区的边界可能由多个多边形组成，我们通常取第一个主边界
          binjiangBoundary.value = district.boundaries[0];
          resolve(binjiangBoundary.value);
        } else {
          reject("未找到滨江区边界数据");
        }
      } else {
        reject("行政区查询失败：" + status);
      }
    });
  });
}
// 高德地图JS API v2.0 提供了 AMap.GeometryUtil 方法
function isPointInPolygon(point, polygon) {
  return AMap.GeometryUtil.isPointInRing(point, polygon);
}
// 步骤4：从完整路径中提取位于滨江区内的线段
function extractBinjiangSection(fullPath, boundary) {
  var sections = []; // 存储所有在区内的线段，可能有多段
  var currentSection = []; // 当前正在构建的线段

  for (var i = 0; i < fullPath.length; i++) {
    var point = new AMap.LngLat(fullPath[i].lng, fullPath[i].lat);

    if (isPointInPolygon(point, boundary)) {
      // 如果当前点在滨江区内，将其加入当前线段
      currentSection.push(point);
    } else {
      // 如果当前点不在滨江区内
      if (currentSection.length > 0) {
        // 并且当前线段不为空，说明一个连续段结束
        sections.push(currentSection);
        currentSection = []; // 重置当前线段
      }
      // 如果当前线段为空，则什么都不做，继续下一个点
    }
  }

  // 循环结束后，检查最后一段
  if (currentSection.length > 0) {
    sections.push(currentSection);
  }

  return sections;
}

// 显示杭州市所有区的名字
const showDistrictNames = async () => {
  const AMap = window.AMap;
  if (!AMap || !map.value) return;

  // 清除现有的区域标记
  clearDistrictMarkers();

  // 杭州市区县列表及对应的中心位置和圆块大小
  const districts = [
    { name: "上城区", position: [120.16, 30.25], radius: 800 },
    { name: "下城区", position: [120.15, 30.28], radius: 700 },
    { name: "江干区", position: [120.2, 30.27], radius: 1000 },
    { name: "拱墅区", position: [120.13, 30.3], radius: 900 },
    { name: "西湖区", position: [120.08, 30.25], radius: 1200 },
    { name: "滨江区", position: [120.2, 30.2], radius: 1900 },
    { name: "萧山区", position: [120.27, 30.17], radius: 1500 },
    { name: "余杭区", position: [120.3, 30.25], radius: 1800 },
    { name: "临安区", position: [120.3, 30.35], radius: 2000 },
    { name: "富阳区", position: [120.25, 30.05], radius: 1000 },
    { name: "桐庐县", position: [120.0, 30.0], radius: 2200 },
    { name: "淳安县", position: [119.5, 29.7], radius: 2500 },
    { name: "建德市", position: [120.0, 30.4], radius: 1900 },
  ];

  // 为每个区县添加标记和圆块
   const markers = districts.flatMap(district => {
    const marker = new AMap.Marker({
      position: district.position,
      title: district.name,
      content: `<div style="
        color: #fff;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: bold;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        border-radius: 16px;
      ">${district.name}</div>`,
      offset: new AMap.Pixel(-30, -15),
      clickable: true,
    })

    if (district.name === '滨江区') {
      marker.on('click', function (e) {
        toggleBusList()
        toggleSubwayList()
        toggleLundu()
        clearDistrictMarkers()
        searchAndDrawBinjiangBoundary()
      })
    }

    const circle = new AMap.Circle({
      center: district.position,
      radius: district.radius,
      fillColor: 'rgba(255, 255, 0, 0.2)',
      fillOpacity: 0.2,
      strokeColor: 'rgba(255, 255, 0, 0.4)',
      strokeOpacity: 0.4,
      strokeWeight: 1,
    })

    return [marker, circle]
  })

  map.value.add(markers)
  districtMarkers.value = markers
};

// 创建大的圆形透明块

// 清除区域标记
const clearDistrictMarkers = () => {
  if (map.value && districtMarkers.value.length > 0) {
    map.value.remove(districtMarkers.value)
    districtMarkers.value = []
  }
}

// 切换区域显示
const toggleDistricts = () => {
  showDistricts.value = !showDistricts.value;
  if (showDistricts.value) {
    showDistrictNames();
  } else {
    clearDistrictMarkers();
  }
};
// 给c#发送消息
const sendMessageToCSharp = (data) => {
  if (window.vuplex) {
    sendMessage(data);
  } else {
    window.addEventListener("vuplexready", sendMessage);
  }
};
function sendMessage({ type, ...data }) {
  window.vuplex.postMessage({
    type,
    ...data,
  });
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initMap();
  });
});
const cleanup = () => {
  // 清理所有覆盖物
  clearMarkers()
  clearDistrictMarkers()
  
  // 清理线路
  Object.keys(subwayLinesObj.value).forEach(key => {
    subwayLinesObj.value[key].forEach(line => map.value?.remove(line))
  })
  
  Object.keys(busLinesObj.value).forEach(key => {
    busLinesObj.value[key].forEach(line => map.value?.remove(line))
  })
  
  // 清理其他覆盖物
  if (myLine.value) map.value?.remove(myLine.value)
  if (lundulineSpolyline.value) map.value?.remove(lundulineSpolyline.value)
  if (binjiangqupolygon.value) map.value?.remove(binjiangqupolygon.value)
  
  // 销毁地图
  if (map.value) {
    map.value.destroy()
    map.value = null
  }
}
onUnmounted(() => {
  cleanup()
});
window.addEventListener("zoomIn", zoomIn);
console.log("放大：zoomIn");
console.log("缩小：zoomOut");
console.log("居中：centerMap");
console.log("热力图：toggleHeatmap");
console.log("显示卫星图：isShowSatellite");
console.log("隐藏卫星图：isHideSatellite");
console.log("地铁：toggleSubwayList"); // 地铁
console.log("公交：toggleBusList"); // 公交
console.log("轮渡：toggleLundu");
console.log("标记点：markersShow");
console.log("路线：toggleRoute");
console.log("区域名称：toggleDistricts");
console.log("滨江区域图：searchAndDrawBinjiangBoundary");

// window.addEventListener("zoomOut", zoomOut);
// window.addEventListener("centerMap", centerMap);

// window.addEventListener("isShowSatellite", isShowSatellite);
// window.addEventListener("isHideSatellite", isHideSatellite);

// window.addEventListener("toggleHeatmap", toggleHeatmap);
// // 地铁
// window.addEventListener("toggleSubwayList", toggleSubwayList);
// // 公交
// window.addEventListener("toggleBusList", toggleBusList);
// //轮渡
// window.addEventListener("toggleLundu", toggleLundu);
// // 标记点
// window.addEventListener("markersShow", markersShow);
// // 路线
// window.addEventListener("toggleRoute", toggleRoute);
// // 区域名称
// window.addEventListener("toggleDistricts", toggleDistricts);
// // 滨江区域图
// window.addEventListener(
//   "searchAndDrawBinjiangBoundary",
//   searchAndDrawBinjiangBoundary
// );

const debouncedZoomIn = debounce(zoomIn, 100)
const debouncedZoomOut = debounce(zoomOut, 100)
const throttledToggleHeatmap = throttle(toggleHeatmap, 300)

window.addEventListener('zoomIn', debouncedZoomIn)
window.addEventListener('zoomOut', debouncedZoomOut)
window.addEventListener('centerMap', debounce(centerMap, 100))
window.addEventListener('isShowSatellite', debounce(isShowSatellite, 100))
window.addEventListener('isHideSatellite', debounce(isHideSatellite, 100))
window.addEventListener('toggleHeatmap', throttledToggleHeatmap)
window.addEventListener('toggleSubwayList', toggleSubwayList)
window.addEventListener('toggleBusList', toggleBusList)
window.addEventListener('toggleLundu', debounce(toggleLundu, 100))
window.addEventListener('markersShow', debounce(markersShow, 100))
window.addEventListener('toggleRoute', debounce(toggleRoute, 100))
window.addEventListener('toggleDistricts', debounce(toggleDistricts, 100))
window.addEventListener('searchAndDrawBinjiangBoundary', searchAndDrawBinjiangBoundary)
</script>

<style scoped>
::v-deep(.amap-logo),
::v-deep(.amap-copyright),
::v-deep(.amap-maptypecontrol) {
  opacity: 0;
}
.amap-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px;
  border: 1px solid #e0e0e0;
  box-sizing: border-box;
  border-radius: 8px;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
  min-height: 500px;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background: rgba(255, 255, 255, 0.95);
  padding: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
}

.control-btn {
  width: 44px;
  height: 44px;
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background: #f8f9fa;
  border-color: #007bff;
  transform: translateY(-2px);
}

.control-btn.active {
  background: #007bff;
  color: white;
  border-color: #0056b3;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.heatmap-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
  min-width: 220px;
}

.heatmap-controls h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.control-group {
  margin-bottom: 16px;
}

.control-group:last-child {
  margin-bottom: 0;
}

.control-group label {
  display: block;
  margin-bottom: 6px;
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.slider {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  appearance: none;
  -webkit-appearance: none;
  transition: background 0.2s;
}

.slider:hover {
  background: #ccc;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.slider::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  color: #dc3545;
  font-weight: 500;
}
</style>
